<?php

include_once '../application/modules/admin/controllers/SuperControllerAdmin.php';
require_once 'Zend/Paginator/Adapter/Interface.php';

class Admin_AdminUsersController extends Admin_SuperController {

    public function indexAction() {

        $this->initModule();

        $strSearch = (string) $this->_request->find;

        $view_page = new Zend_Session_Namespace('view_apage');
        $onPage = $view_page->on_page;

        $page = (int) $this->_request->page;
        if (empty($page))
            $page = 1;

        $this->view->order_field = isset($this->_request->order_field) ? $this->_request->order_field : 'id';
        $this->view->order_dir = isset($this->_request->order_dir) ? $this->_request->order_dir : 'ASC';

        $this->view->tableColumn = array(
            0 => array(
                'title' => 'id',
                'field' => 'id'
            ),
            1 => array(
                'title' => 'login',
                'field' => 'login'
            ),
            2 => array(
                'title' => 'role',
                'field' => 'role'
            ),
            3 => array(
                'title' => 'last_active',
                'field' => 'last_active'
            ),
            4 => array(
                'title' => 'Change'
            ),
        );

        $qAr = array(
            'order_field' => $this->view->order_field,
            'order_dir' => $this->view->order_dir
        );

        $usersModel = new Admin_Model_AdminUsers();
        $this->view->Info = $usersModel->getUsers($qAr);
        $this->view->mc = new Memcache();
        $this->view->mc->connect("localhost", 11211);

        $this->view->back = $this->_request->back;
    }

    protected function initModule() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
        }
        if ($this->_request->event == 'removeRow')
            $this->OnRemoveRow($this->_request->getPost());
        if ($this->_request->event == 'update')
            $this->OnUpdate($this->_request->getPost());
        if ($this->_request->event == 'insert')
            $this->OnInsert($this->_request->getPost());
    }

    public function accessListAction() {

        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
            if ($this->_request->event == 'removeRow')
                $this->OnRemoveGroup($this->_request->getPost());
            if ($this->_request->event == 'createNewGroup')
                $this->OnCreateNewGroup($this->_getParam('role_name'), $this->_getParam('role_id'));
        }

        $this->view->order_field = isset($this->_request->order_field) ? $this->_request->order_field : 'id';
        $this->view->order_dir = isset($this->_request->order_dir) ? $this->_request->order_dir : 'ASC';

        $this->view->tableColumn = array(
            0 => array(
                'title' => 'id',
                'field' => 'id'
            ),
            1 => array(
                'title' => 'title',
                'field' => 'title'
            ),
            2 => array(
                'title' => 'Change'
            )
        );

        $qAr = array(
            'order_field' => $this->view->order_field,
            'order_dir' => $this->view->order_dir
        );

        $AGM = new Admin_Model_AdminGroups();
        $this->view->Info = $AGM->getGroups($qAr);

        $this->view->back = $this->_request->back;
    }

    public function OnRemoveRow() {
        $id = (int) $this->_getParam('id');
        if ($id) {
            $model = new Admin_Model_AdminUsers();
            $info = $model->removeUser($id);
        }
    }

    public function OnCreateNewGroup($groupName, $copy_group_id = NULL) {
        if ($groupName) {
            $copy_group_id = (int) $copy_group_id;
            $AGM = new Admin_Model_AdminGroups;
            $count = $AGM->getCountGroupsByName($groupName);
            if (!empty($count)) {
                MessBox::setMessage('this_group_exists');
                return;
            }
            $AGM->insertGroup($groupName, $copy_group_id);
        }
    }

    public function OnRemoveGroup() {
        $id = (int) $this->_getParam('id');
        if ($id) {
            $model = new Admin_Model_AdminGroups();
            $info = $model->removeGroup($id);
        }
    }

    public function refreshInfoBarAction() {
        Zend_Layout::getMvcInstance()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);

        $this->cache = $this->view->cache;
        $this->countModerateTasks = $this->view->countModerateTasks;
        $this->countModerateTasksSms = $this->view->countModerateTasksSms;
        $this->countModerateAB = $this->view->countModerateAB;
        $this->countModerateSmtp = $this->view->countModerateSmtp;

        include '../application/modules/admin/layouts/scripts/info-bar.phtml';
    }

    protected function check_data(&$data) {
        $result = true;
        if ($data['event'] == 'insert') {
            $model = new Admin_Model_AdminUsers();
            if ($model->getCountUsersByLogin($data['login'])) {
                MessBox::setMessage('user_login_is_exists');
                $result = false;
            }
        }
        return $result;
    }

    public function OnUpdate($data) {
        if ($this->check_data($data)) {
            if (isset($data['pass']) && !empty($data['pass'])) {
                $data['password'] = Admin_Model_Account::cryptString($data['pass']);
            }
            if (isset($data['pass'])) {
                unset($data['pass']);
            }
            if (isset($data['confirm_password'])) {
                unset($data['confirm_password']);
            }
            if ($data['tz'] != 'NULL') {
                $tz = Application_Model_Date::getOffset($data['tz']);
                if ($tz) {
                    $timeZone = $tz['gmtOffsetDB'];
                } else {
                    $timeZone = '0';
                }
                $data['time_zone'] = $timeZone;
                $data['locale'] = $data['tz'];

                $admin_account = new Zend_Session_Namespace('admin_account');
                if ($data['id'] == $admin_account->id) {
                    $admin_account->time_zone = $data['time_zone'];
                    $admin_account->locale = $data['locale'];
                }
            }
            if (isset($data['tz'])) {
                unset($data['tz']);
            }
            $model = new Admin_Model_AdminUsers();
            $model->updateUser($data);
        }
    }

    public function OnInsert($data) {
        if ($this->check_data($data)) {
            $password = trim($data['pass']);
            if (empty($password)) {
                MessBox::setMessage('enter_password');
                return false;
            }
            if (isset($data['pass']) && !empty($data['pass'])) {
                $data['password'] = Admin_Model_Account::cryptString($data['pass']);
            }
            if (isset($data['pass'])) {
                unset($data['pass']);
            }
            if (isset($data['confirm_password'])) {
                unset($data['confirm_password']);
            }
            if ($data['tz'] != 'NULL') {
                $tz = Application_Model_Date::getOffset($data['tz']);
                if ($tz) {
                    $timeZone = $tz['gmtOffsetDB'];
                } else {
                    $timeZone = '0';
                }
                $data['time_zone'] = $timeZone;
                $data['locale'] = $data['tz'];
            }
            if (isset($data['tz'])) {
                unset($data['tz']);
            }
            $model = new Admin_Model_AdminUsers();
            $model->insertUser($data);
        }
    }

    public function getAjaxDataUserAction() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
        }
        $admin_account = new Zend_Session_Namespace('admin_account');
        $adminUsers = array();
        if ($admin_account->role_id === 1) {
            $adminUsers[] = array('name' => 'login', 'type' => 'str', 'valid' => true,);
            $adminUsers[] = array('name' => 'pass', 'id' => 'password', 'type' => 'password');
            $adminUsers[] = array('name' => 'confirm_password', 'id' => 'confirm', 'type' => 'password');
            $adminUsers[] = array('name' => 'role_id', 'type' => 'build', 'function' => 'getRoleSelect',);
        }

        $id = (int) $this->_getParam('id');
        $this->view->event = (string) $this->_getParam('event');
        if ($id || $this->view->event = 'insert') {
            if ($id) {
                $AdminUsersModel = new Admin_Model_AdminUsers();
                $this->view->info = $AdminUsersModel->getUsersById($id);
                $this->view->id = $id;
                $this->view->info['fields'] = $this->addValue($adminUsers, $this->view->info);
                $this->view->info['title'] = 'edit_user';
            } else {
                $adminUsers[1]['valid'] = true;
                $adminUsers[2]['valid'] = true;
                $this->view->info = array();
                $this->view->info['fields'] = $adminUsers;
                $this->view->info['title'] = 'user_create';
            }
        }
    }

    public function getAjaxDataGroupAction() {
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout->disableLayout();
        }
        $id = (int) $this->_getParam('id');
        if (!empty($id)) {
            $AGM = new Admin_Model_AdminGroups();

            $this->view->id = $id;

            $this->view->group = $AGM->getGroupsById($id);
            if (!empty($this->view->group['perm_view'])) {
                $this->view->group['perm_view'] = json_decode($this->view->group['perm_view'], true);
            } else {
                $this->view->group['perm_view'] = array();
            }
            $this->view->permisions = json_decode($AGM->getBasePermissions(), true);
        }
    }

    public function editResourceAction() {
        $this->_helper->layout->disableLayout();

        $AGM = new Admin_Model_AdminGroups();
        $this->view->permisions = json_decode($AGM->getBasePermissions(), true);
    }

    public function updateResourceAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);

        $data = $this->getRequest()->getParams();
        if (is_array($data) && count($data)) {
            unset($data['module'], $data['controller'], $data['action']);
            $AGM = new Admin_Model_AdminGroups();
            $AGM->updateBasePermissions($data);
        }
    }

    public function createNewGroupAction() {
        $this->_helper->layout->disableLayout();
    }

    public function updateGroupAction() {
        Zend_Layout::getMvcInstance()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
        $data = $this->getRequest()->getParams();

        if (!empty($data['groupID'])) {

            $perm = $structure = array();

            $temp = explode('|', $data['perm']);
            if (is_array($temp) && count($temp)) {
                foreach ($temp as $tmp) {
                    if (!empty($tmp)) {
                        $tm = explode(':', $tmp);
                        if (!empty($tm[0]) && !empty($tm[1]))
                            $perm[] = $tm;
                    }
                }
            }

            $temp = explode('&', $data['structure']);
            if (is_array($temp) && count($temp)) {
                foreach ($temp as $tmp) {
                    if (!empty($tmp)) {
                        $tm = explode('=', $tmp);
                        if (!empty($tm[0]) && !empty($tm[1]))
                            $structure[] = $tm[0];
                    }
                }
            }

            $AGM = new Admin_Model_AdminGroups();
            $AGM->updateGroup($data['groupID'], json_encode($perm), json_encode($structure));
        }
    }

    public function slamRememberAction() {
        Zend_Layout::getMvcInstance()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
        $event = (string) $this->_request->event_menu;
        $cname = (string) $this->_request->cname;
        $text = $this->_request->val;
        if (!empty($event) && !empty($text)) {
            $exp_date = time() + 60 * 60 * 24 * 31 * 12;

            $slam = array();
            if (!empty($_COOKIE[$cname]))
                $slam = unserialize(stripcslashes($_COOKIE[$cname]));

            if ($event == 'add') {
                if (!in_array($text, $slam))
                    $slam[] = $text;
                setcookie($cname, serialize($slam), $exp_date, '/', $this->getRequest()->getHttpHost());
            }

            if ($event == 'remove') {
                $key = array_search($text, $slam);
                //if ($key !== false) {
                unset($slam[$key]);
                setcookie($cname, serialize($slam), $exp_date, '/', $this->getRequest()->getHttpHost());
                //}
            }
            //setcookie( $cname, '', $exp_date, '/', $this->getRequest()->getHttpHost() );
        }
    }

    public function updateNewRuleAction() {
        Zend_Layout::getMvcInstance()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
        $sSectionName = trim($this->_request->section_name);
        $aNewRules = $this->_request->new_rules;
        if (!empty($sSectionName) && !empty($aNewRules)) {
            $AGRPM = new Admin_Model_AdminGroups();
            $AGRPM->addNewRulesToGroups($sSectionName, $aNewRules);
        }
    }

}
